﻿using Hydrogen.ULib.Attributes;
using System;
using System.Collections.Generic;
using System.Xml;

namespace Hydrogen.MarkovChain
{
    /// <summary>
    /// 规则根节点
    /// </summary>
    [RuleNodeName(RuleConstant.ROOT), Serializable]
    public class RuleRoot : RuleNodeBase, IRuleNodeExcuteable
    {
        /// <summary>
        /// 子节点类型
        /// </summary>
        private static List<string> _chileNodeTypes = new List<string>()
        {
            RuleConstant.NODE_SP,
            RuleConstant.NODE_SEQUENCE,
        };

        [UnityEngine.SerializeField, ReadOnly]
        private List<RuleNodeBase> _children;

        public List<RuleSP> RuleSPs { get; } = new List<RuleSP>();
        private List<IRuleNodeExcuteable> _excuteableNodes = new List<IRuleNodeExcuteable>();


        public RuleRoot(XmlNode xmlNode) : base(xmlNode)
        {
            this._children = GetChildNode(xmlNode, _chileNodeTypes);

            foreach (var item in this._children)
            {
                if (item is RuleSP) this.RuleSPs.Add(item as RuleSP);
                else if (item is IRuleNodeExcuteable) this._excuteableNodes.Add(item as IRuleNodeExcuteable);
            }

            if (this.RuleSPs.Count == 0) this.RuleSPs.Add(new RuleSP());
        }

        public override void Reset()
        {
            base.Reset();

            foreach (var item in _children) item.Reset();
        }

        private int _currSequenceIndex = 0;
        public bool TryExcute(Func<IRuleNodeSolidReplace, bool> excuteAcvive)
        {
            for (int i = this._currSequenceIndex; i < this._children.Count; i++)
            {
                if (this._children[i] is RuleSequence)
                {
                    if (!(this._children[i] as RuleSequence).TryExcute(excuteAcvive)) _currSequenceIndex++;
                    else return true;
                }
            }

            return false;
        }
    }
}
